package com.huike.web.controller.common;

import com.huike.config.HuiKeConfig;
import com.huike.core.controller.BaseController;
import com.huike.core.domain.AjaxResult;
import com.huike.oss.client.OSSAliyunFileStorageService;
import com.huike.utils.PDFUtil;
import com.huike.utils.StringUtils;
import com.huike.utils.file.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/common")
public class CommonController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private OSSAliyunFileStorageService fileStorageService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = HuiKeConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file, String idCardNo) throws Exception
    {
        try
        {
            //文件名--->UUID.后缀
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString()+extension;

            //把文件上传到oss中
            String url = fileStorageService.store(filename, file.getInputStream());

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", url);
            ajax.put("newFileName", filename);
            ajax.put("originalFilename", file.getOriginalFilename());

            //解析PDF内容
            String content = PDFUtil.pdfToString(file.getInputStream());
            redisTemplate.opsForValue().set("PDF:" + idCardNo, content,2, TimeUnit.HOURS);

            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}
